import 'dart:async';

import 'package:flutter/material.dart';


class ContentSelection extends StatefulWidget {
  @override
  _ContentSelectionState createState() => _ContentSelectionState();
}

class _ContentSelectionState extends State<ContentSelection> {

  int leftSeconds = 3700;

  late Timer _timer;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _startTimer();
  }

  //根据总秒数转换为对应的 hh:mm:ss 格式
  static String constructTime(int seconds) {
    int day = seconds ~/3600 ~/24;
    int hour = seconds ~/ 3600 %24;
    int minute = seconds % 3600 ~/ 60;
    int second = seconds % 60;
    // if(day != 0){
    //   return formatTime(day)+'天'+formatTime(hour) + "小时" + formatTime(minute) + "分" + formatTime(second)+'秒';
    // }else if(hour != 0){
    //   return formatTime(hour) + ":" + formatTime(minute) + ":" + formatTime(second)+'';
    // }else if(minute !=0){
    //   return formatTime(minute) + ":" + formatTime(second)+'';
    // }else if(second!=0){
    //   return formatTime(second)+'';
    // }else {
    //   return '';
    // }

    if(day != 0){
      return formatTime(day)+'天'+formatTime(hour) + "小时" + formatTime(minute) + "分" + formatTime(second)+'秒';
    }else if(hour != 0){
      return formatTime(hour) + ":" + formatTime(minute) + ":" + formatTime(second)+'';
    }else if(minute !=0){
      return formatTime(hour) + ":" + formatTime(minute) + ":" + formatTime(second)+'';
    }else if(second!=0){
      return formatTime(hour) + ":" + formatTime(minute) + ":" + formatTime(second)+'';
    }else {
      return formatTime(hour) + ":" + formatTime(minute) + ":" + formatTime(second)+'';
    }

  }


  //数字格式化，将 0~9 的时间转换为 00~09
  static String formatTime(int timeNum) {
    return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
  }

  _cancelTimer() {//界面销毁时记得取消计时器
    if (_timer != null) {
      _timer.cancel();

    }
  }


//需要使用时调用开始倒计时
  _startTimer() {
    //设置 1 秒回调一次
    const period = const Duration(seconds: 1);
    _timer = Timer.periodic(period, (timer) {
      print(leftSeconds);
      //秒数减一，更新界面
      setState(() {
        leftSeconds --;
      });
      if (leftSeconds == 0) {
      //倒计时秒数为0，取消定时器
      print('我被取消了  ');
      _cancelTimer();
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer.cancel();
  }



  @override
  Widget build(BuildContext context) {
    return Expanded(child: Center(child: Text("敬请期待"),));
  }
}
